'use strict'

let WebSocket = require('ws')
let util = require('util')
let userServerConfig = require('../config/serverConfig').userServerConfig
let nodeServerConfig = require('../config/serverConfig').nodeServerConfig
let rc4a = require('./rc4a.js')

class UserSerClient {
  constructor() {
    this.callbacks = {}
    this.reqId = 1
    this.client = null
  }

  createClient() {
    let self = this
    this.client = new WebSocket(`ws://${userServerConfig.ip}:${userServerConfig.port}`)
    this.client.on('open', function open() {
        console.log('连接用户服务器成功')
    })

    this.client.on('message', function message(data, flags) {
      try {
        if (!Buffer.isBuffer(data) || data.length <= 4) {
          return
        }
        data = rc4a.decodeBuffer(data)
        data = JSON.parse(data)
        if (!util.isObject(data.msg)) {
          data.msg = {}
        }
      } catch (e) {
        return
      }
      Log(data)
      if (data.reqId) {
        var i = data.reqId
        if (self.callbacks[i]) {
          self.callbacks[i](data.msg)
          delete self.callbacks[i]
        }
      }
    })
  }

  request(route, msg, cb) {
    let data
    if (cb) {
      this.callbacks[this.reqId] = cb
      data = {
        route: route,
        msg: msg,
        reqId: this.reqId
      }
      this.reqId += 1
    } else {
      data = {
        route: route,
        msg: msg
      }

    }
    data = JSON.stringify(data)
    this.client.send(rc4a.encodeStr(data))
  }
}

let userSerClient = new UserSerClient()
userSerClient.createClient()
module.exports = userSerClient
